# -*- coding: utf-8 -*-
import pymysql
from .mysql import *


def check_authcode(uid, authcode):
    with mysql(db="typecho") as cur:
        cur.execute(
            """
            SELECT *
            FROM typecho_users
            WHERE `uid` = %s AND `authCode` = %s;
            """,
            (uid, authcode))
        data = cur.fetchone()
        if not data:
            return False, "uid或authCode错误"
        else:
            return True, data


def is_admin(uid):
    with mysql(db="typecho") as cur:
        cur.execute(
            """
            SELECT `group`
            FROM typecho_users
            WHERE `uid` = %s;
            """,
            (uid, ))
        data = cur.fetchone()
        if not data:
            return False, "uid错误"
    if data["group"] != "administrator":
        with mysql(db="BBS") as cur:
            cur.execute(
                """
                SELECT permission
                FROM admin
                WHERE uid = %s;
                """,
                (uid, ))
            return True, bool(cur.fetchone())
    return True, True


def set_admin(uid, authcode, admin_uid):
    s, data = check_authcode(uid, authcode)
    if not s:
        return False, data
    with mysql(db="typecho") as cur:
        cur.execute(
            """
            SELECT screenName
            FROM typecho_users
            WHERE uid = %s;
            """,
            (admin_uid, ))
        admin_data = cur.fetchone()
        if not admin_data:
            return False, "所设置的管理员uid不存在"
        admin_name = admin_data["screenName"]
    with mysql(db="BBS") as cur:
        cur.execute(
            """
            SELECT permission
            FROM admin
            WHERE uid = %s;
            """,
            (admin_uid, ))
        permission = cur.fetchone()
        if permission:
            return False, "该用户已是管理员"
        if data["group"] == "administrator":
            cur.execute(
                """
                INSERT INTO admin
                VALUES (%s, %s, "administrator");
                """,
                (admin_uid, admin_name))
            return True, admin_uid
        else:
            return False, "权限不足"
